package org.elasticsearch.plugin.analysis.hanlp;

import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.Set;
import java.util.TimerTask;

import org.apache.logging.log4j.Logger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.util.set.Sets;

import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.dictionary.CustomDictionary;

public class DictReloadTask extends TimerTask {

    private Logger logger = Loggers.getLogger(DictReloadTask.class, "hanlp dict task");

    @Override
    public void run() {
        String[] oldPaths = HanLP.Config.CustomDictionaryPath;
        Set<String> oldPathSet = Sets.newHashSet(oldPaths);
        for (String oldPath : oldPaths) {
            oldPathSet.add(oldPath.split(" ")[0]);
        }
        String root = oldPaths[0].substring(0, oldPaths[0].lastIndexOf(File.separator));
        File[] subFiles = new File(root).listFiles(new FileFilter() {
            @Override
            public boolean accept(File path) {
                if (path == null || path.getAbsolutePath() == null || oldPathSet.contains(path.getAbsolutePath())) {
                    return false;
                }
                if (!path.getName().endsWith("txt")) {
                    return false;
                }
                return true;
            }
        });
        if (subFiles.length < 1) {
            logger.debug("there is no need to reload dict");
            return;
        }
        String[] addPaths = new String[subFiles.length];
        for (int i = 0; i < subFiles.length; i++) {
            addPaths[i] = subFiles[i].getPath();
        }
        logger.info("need to add path: " + Arrays.toString(addPaths));
        String[] customArray = Arrays.copyOf(oldPaths, oldPaths.length + addPaths.length);
        System.arraycopy(addPaths, 0, customArray, oldPaths.length, addPaths.length);
        logger.debug("new dict path: " + Arrays.toString(customArray));
        HanLP.Config.CustomDictionaryPath = customArray;
        logger.info("begin reload dict");
        CustomDictionary.reload();
        logger.info("finish reload dict");
    }

}
